package com.yingyi.basic.controller;


import com.yingyi.basic.util.FastDfsUtils;
import com.yingyi.basic.util.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastdfs")
public class FastDfsController {

    /**
     * name	上传的文件字段名	string	—	file
     * 根据查询element-ui手册， 上传文件字段名的默认名字为file
     * 故使用file名字的变量接收
     *
     * 参数值的注入注解为
     *  @RequestPart(value = "file", required = true)
     * @param file
     * @return
     */
    @PostMapping
    public JsonResult upload (@RequestPart(value = "file", required = true) MultipartFile file){
        try {
            String originalFilename = file.getOriginalFilename();

            //获取后缀名（不包含.）
            String suffix = originalFilename.substring(originalFilename.lastIndexOf('.') + 1);


            //getBytes() Return the contents of the file as an array of bytes.
            String remotePath = FastDfsUtils.upload(file.getBytes(), suffix);

            return JsonResult.me().setResultObj(remotePath);

        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMessage("上传失败，稍后重试！");
        }
    }


    /**
     * 前端请求："/fastdfs?path="+filePath
     *  http://localhost:8080/fastdfs?path=/group1/xxx/yyy/...
     *
     *  注意参数的注入注解
     *  @RequestParam(value = "path", required = true)
     *
     *  区别restful风格的 http://localhost:8080/dept/1
     *           ${id}
     * @return
     */
    @DeleteMapping
    public JsonResult delete(@RequestParam(value = "path", required = true) String path){
        try {
            //解析path 获取组名、文件名
            String tempPath = path.substring(1);    // group1/xxx/yyy/...
            String groupName = tempPath.substring(0, tempPath.indexOf('/')); // group1

            String fileName = tempPath.substring(tempPath.indexOf('/') + 1); // xxx/yyy/...

            //删除文件 group1  00/00/FF/CgAIC2LeFH-ADvQRAABfAIlhuJA853.jpg
            FastDfsUtils.delete(groupName, fileName);
            return JsonResult.me();

        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMessage("删除失败，稍后重试");
        }
    }
}
